import React, {useEffect, useState} from 'react';
import {makeStyles} from "@material-ui/core";
import Image from '../img/bg.jpg'
import TextField from "@material-ui/core/TextField";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import {Link, useHistory} from "react-router-dom";
import Box from "@material-ui/core/Box";
import {anonymousInstance} from "../api";
import Alert from "@material-ui/lab/Alert";
import CircularProgress from "@material-ui/core/CircularProgress";
import Validator from "validator";
import {useAuth} from "../contexts/AuthContext";

const useStyles = makeStyles(theme => ({
    root: {
        backgroundImage: `url(${Image})`,
        height: "100vh",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
        backgroundSize: "cover",
        display: "flex",
    },
    paper: {
        maxWidth: "500px",
        height: "600px",
        margin: "auto",
        padding: theme.spacing(8),
        paddingTop: theme.spacing(5),
    },
    form: {
        '& > *': {
            width: "100%",
            marginBottom: theme.spacing(3),
        }

    },
    header: {
        textAlign: "center",
        marginBottom: theme.spacing(3),
    },
    box: {
        fontSize: theme.spacing(2),
        marginTop: theme.spacing(2),
        marginBottom: theme.spacing(2),
    }
}))


const Signup = () => {
    const classes = useStyles()
    const history = useHistory()

    const [loading, setLoading] = useState(false)
    const [username, setUsername] = useState('')
    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')
    const [re_password, setRePassword] = useState('')
    const [errors, setErrors] = useState({})

    const {isAuthenticated} = useAuth()

    // 登录用户如果访问/signup页面，重定向到主页
    useEffect(() => {
        if (isAuthenticated)
            history.push('/')
    }, [isAuthenticated, history])


    // 前端校验
    const validate = ({email, password}) => {
        const errors = {}
        if (!username) errors.username = '用户名不能为空'
        if (!email) errors.email = '邮箱不能为空'
        if (!password) errors.password = '密码不能为空'
        if (!re_password) errors.re_password = '确认密码不能为空'

        if (password !== re_password) {
            // 与后端保持一致
            errors.non_field_errors = '确认密码和密码不匹配'
        }
        if (email && !Validator.isEmail(email)) errors.email = '无效邮箱'
        return errors
    }

    const handleSubmit = async (e) => {
        e.preventDefault()

        try {
            setErrors({})
            setLoading(true)

            const errors = validate({username, email, password, re_password})

            // 有错误不往后端提交
            if (Object.keys(errors).length !== 0) {
                setErrors(prevState => ({...prevState, ...errors}))
                setLoading(false)
            } else {
                // Django后端的DJOSER需要设置 USER_CREATE_PASSWORD_RETYPE = True 才会有re_password字段
                await anonymousInstance.post('/users/', {username, email, password, re_password})
                setLoading(false)
                // 注册成功重定向到登录页面 TODO:应该提醒用户登录??? message
                history.push('/login')
            }

        } catch (e) {
            setLoading(false)

            if (e.response && e.response.status === 400) {
                const data = e.response.data
                // 后端特有的错误
                if (data.hasOwnProperty('non_field_errors'))
                    setErrors({non_field_errors: "确认密码和密码不匹配"})
                else
                    setErrors(data)
            } else {
                setErrors({'detail': '注册失败！服务器错误,管理员正在解决...'})
            }
        }
    }

    return (
        <div className={classes.root}>
            <Paper className={classes.paper} elevation={0}>

                {loading && <CircularProgress/>}

                <Typography variant="h3" className={classes.header}>注册新账号</Typography>

                {errors.detail && (
                    <Alert severity="error">{errors.detail}</Alert>
                )}

                {errors.non_field_errors && (
                    <Alert severity="error">{errors.non_field_errors}</Alert>
                )}

                <Box display="flex" justifyContent="flex-end" className={classes.box}>
                    已经有账号?
                    <Link to="/login">登录</Link>
                </Box>
                <form noValidate className={classes.form} onSubmit={handleSubmit}>
                    <TextField
                        error={!!errors.username}
                        label="用户名"
                        variant="outlined"
                        name="username"
                        onChange={e => {
                            setErrors(prevState => ({...prevState, username: ''}))
                            setUsername(e.target.value)
                        }}
                        helperText={!!errors.username && errors.username}
                    />
                    <TextField
                        error={!!errors.email}
                        label="邮箱"
                        variant="outlined"
                        name="username"
                        type="email"
                        onChange={e => {
                            setErrors(prevState => ({...prevState, email: ''}))
                            setEmail(e.target.value)
                        }}
                        helperText={!!errors.email && errors.email}
                    />
                    <TextField
                        error={!!errors.password || !!errors.non_field_errors}
                        label="密码"
                        variant="outlined"
                        name="password"
                        type="password"
                        onChange={e => {
                            setErrors(prevState => ({...prevState, password: '', non_field_errors: ''}))
                            setPassword(e.target.value)
                        }}
                        helperText={!!errors.password && errors.password}
                    />
                    <TextField
                        error={!!errors.re_password || !!errors.non_field_errors}
                        label="确认密码"
                        variant="outlined"
                        name="re_password"
                        type="password"
                        onChange={e => {
                            setErrors(prevState => ({...prevState, re_password: '', non_field_errors: ''}))
                            setRePassword(e.target.value)
                        }}
                        helperText={!!errors.re_password && errors.re_password}
                    />
                    <Button variant="contained" color="primary" size="large" type="submit">
                        注册
                    </Button>
                </form>
            </Paper>
        </div>
    );
};

export default Signup;